package com.xnew.utils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class SendMail {
    private String mailSmtp ;//= "smtp.mxhichina.com";
    private String sender ;//= "guomr@xnewtech.com";
    private String senderpwd ;//= "guomengran_1979";
    /*
     * 构造函数
     */
    public SendMail(String mailSmtp,String sender, String senderpwd) throws UnsupportedEncodingException {
        System.out.println("mailSmtp:" + mailSmtp + ";sender:" + sender + ";senderpwd:" + senderpwd );
        this.mailSmtp = mailSmtp;
        this.sender = sender;
        this.senderpwd = senderpwd;
    }
    /**
     *
     * @param receviers 接收人（多个接收人，以‘;’号分割）
     * @param content 内容
     * @param subject 主题
     */
    public void sendMail(String receviers,final String content,String subject
    ) throws Exception{
        System.out.println("mailSmtp:" + mailSmtp + ";sender:" + sender + ";senderpwd:" + senderpwd );
        try {

            Properties props = System.getProperties();
            props.put("mail.smtp.host", mailSmtp);
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(true);
            InternetAddress fromAddress = new InternetAddress(sender);
            if(null != receviers && !"".equals(receviers)){
                String[] recArry = receviers.split(";");
                for (int i = 0; i < recArry.length; i++) {
                    InternetAddress toList[] = InternetAddress.parse(recArry[i], false);
                    MimeMessage msg = new MimeMessage(session);
                    msg.setFrom(fromAddress);
                    msg.setSentDate(new Date());
                    msg.addRecipients(MimeMessage.RecipientType.TO, toList);
                    msg.setSubject(subject,"UTF-8");
                    MimeBodyPart part = new MimeBodyPart();
                    part.setContent(content,"text/html;charset=UTF-8");
                    MimeMultipart mm = new MimeMultipart();
                    mm.addBodyPart(part);
                    msg.setContent(mm);
                    msg.saveChanges();
                    Transport transport = session.getTransport("smtp");
                    transport.connect(mailSmtp, sender, senderpwd);
                    transport.sendMessage(msg, toList);
                    transport.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送带附件邮件
     * @param receviers 接收邮件地址多个以‘;’隔开
     * @param content 内容
     * @param subject 标题
     * @param fileSour 文件路径
     * @param v_file_name 文件名称
     */
    public void sendMailFujian(String receviers,final String content,String subject,String fileSour,String v_file_name) throws Exception{
        try {
            String file_name=v_file_name;
            Properties props = System.getProperties();
            props.put("mail.smtp.host", "smtp.mxhichina.com");
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(false);
            InternetAddress fromAddress = new InternetAddress(sender);
            if(null != receviers && !"".equals(receviers)){
                String[] recArry = receviers.split(";");
                for (int i = 0; i < recArry.length; i++) {
                    InternetAddress toList[] = InternetAddress.parse(recArry[i], false);
                    MimeMessage msg = new MimeMessage(session);
                    msg.setFrom(fromAddress);
                    msg.setSentDate(new Date());
                    msg.addRecipients(MimeMessage.RecipientType.TO, toList);
                    msg.setSubject(subject,"GBK");
                    BodyPart part= new MimeBodyPart();
                    MimeBodyPart part_x = new MimeBodyPart();

                    part_x.setContent(content,"text/html;charset=UTF-8");
                    MimeMultipart mm = new MimeMultipart();
                    DataSource source = new FileDataSource(fileSour);//原本地文件写法
                    part.setDataHandler(new DataHandler(source));//原本地文件写法
                    part.setFileName(MimeUtility.encodeText(file_name));

                    mm.addBodyPart(part);
                    mm.addBodyPart(part_x);
                    msg.setContent(mm);
                    msg.saveChanges();
                    Transport transport = session.getTransport("smtp");
                    transport.connect(mailSmtp, sender, senderpwd);
                    transport.sendMessage(msg, toList);
                    transport.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送带附件邮件
     * @param receviers 接收邮件地址多个以‘;’隔开
     * @param content 内容
     * @param subject 标题
     * @param fileList 文件列表
     */
    public void sendMailFujianList(String receviers,final String content,String subject,List<String> fileList) throws Exception{
        try {
            Properties props = System.getProperties();
            props.put("mail.smtp.host", mailSmtp);
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(false);
            InternetAddress fromAddress = new InternetAddress(sender);
            if(null != receviers && !"".equals(receviers)){
                String[] recArry = receviers.split(";");
                for (int i = 0; i < recArry.length; i++) {
                    InternetAddress toList[] = InternetAddress.parse(recArry[i], false);
                    MimeMessage msg = new MimeMessage(session);
                    msg.setFrom(fromAddress);
                    msg.setSentDate(new Date());
                    msg.addRecipients(MimeMessage.RecipientType.TO, toList);
                    msg.setSubject(subject,"GBK");
                    MimeBodyPart part_x = new MimeBodyPart();

                    part_x.setContent(content,"text/html;charset=UTF-8");
                    MimeMultipart mm = new MimeMultipart();
                    System.out.println("fileList:" + fileList.toString());
                    if(fileList!=null && fileList.size()>0){
                        for(String file : fileList){
                            System.out.println("file:" + file);
                            String fileSour = file;//file.substring(0,file.lastIndexOf("\\") + 1);System.out.println("fileSour:" + fileSour);
                            String fileName = file.substring(file.lastIndexOf("\\") + 1);
                            System.out.println("fileName:" + fileName);
                            if(fileSour!=null && fileName!=null && !fileSour.trim().equals("") && !fileName.trim().equals("")){
                                MimeBodyPart attachmentPart =new MimeBodyPart();//用于装载邮件附件
                                FileDataSource fds=new FileDataSource(fileSour);//从文件的绝对路径处获取数据源
                                attachmentPart.setDataHandler(new DataHandler(fds));
                                attachmentPart.setFileName(MimeUtility.encodeText(fileName));
                                mm.addBodyPart(attachmentPart);
                            }
                        }
                    }
                    mm.addBodyPart(part_x);
                    msg.setContent(mm);
                    msg.saveChanges();
                    Transport transport = session.getTransport("smtp");
                    transport.connect(mailSmtp, sender, senderpwd);
                    transport.sendMessage(msg, toList);
                    transport.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void execute() {}

    /**测试*/
    public static void main(String[] args) throws UnsupportedEncodingException {
        //邮件
        try {
            System.out.println("发送邮件开始");

            String emailAry = "zhongzh@xnewtech.com" ;//接收邮件的Email地址
            String receiver = "" ;//接收人SUI_ID
            String title = "邮件标题测试" ;//邮件标题
            String content = "邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容邮件内容" ;//邮件内容
            String sender = "" ;//邮件发送人SUI_ID
            String senderEmail = "" ;//发送邮件的Email地址
            SendMail sendMail = new SendMail("smtp.mxhichina.com","guomr@xnewtech.com","guomengran_1979");
            //sendMail.sendMail(emailAry, content, title);
            List<String> fileList = new ArrayList<String>();
            String v_file_name1 = "C:\\证券业协会项目\\调解平台调整内容 (1).docx";
            String v_file_name2 = "C:\\证券业协会项目\\调解平台调整内容.docx";
            String v_file_name3 = "C:\\证券业协会项目\\考生个人健康声明-828.pdf";
            String v_file_name4 = "C:\\证券业协会项目\\从业人员管理系统前端配置.docx";
            String v_file_name5 = "C:\\证券业协会项目\\统一单点登录门户对接工作内容.xlsx";
            fileList.add(v_file_name1);System.out.println(v_file_name1);
            fileList.add(v_file_name2);System.out.println(v_file_name2);
            fileList.add(v_file_name3);System.out.println(v_file_name3);
            fileList.add(v_file_name4);System.out.println(v_file_name4);
            fileList.add(v_file_name5);System.out.println(v_file_name5);
            String fileSour = v_file_name1.substring(0,v_file_name1.lastIndexOf("\\") + 1);System.out.println("fileSour:" + fileSour);
            String fileName = v_file_name1;System.out.println("fileName:" + fileName);
            //sendMail.sendMail(emailAry,content,title);
            //sendMail.sendMailFujian(emailAry,content,title,fileSour,fileName);
            sendMail.sendMailFujianList(emailAry,content,title,fileList);
            System.out.println("发送邮件结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
